<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模型缓存测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            margin: 5px;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            background: #007bff;
            color: white;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .status {
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
            background: #f8f9fa;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .cache-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin: 10px 0;
        }
        .model-list {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin: 10px 0;
        }
        .model-item {
            padding: 5px;
            margin: 2px 0;
            background: #f8f9fa;
            border-radius: 3px;
        }
        .cached {
            background: #d4edda;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>模型缓存测试工具</h1>
        
        <div class="test-section">
            <h3>1. Service Worker 状态</h3>
            <div id="sw-status" class="status">检测中...</div>
            <button onclick="registerServiceWorker()">注册 Service Worker</button>
            <button onclick="unregisterServiceWorker()">注销 Service Worker</button>
        </div>

        <div class="test-section">
            <h3>2. 缓存状态</h3>
            <div id="cache-status" class="status">加载中...</div>
            <button onclick="checkCacheStatus()">刷新缓存状态</button>
            <button onclick="clearAllCache()">清空所有缓存</button>
        </div>

        <div class="test-section">
            <h3>3. 模型预加载测试</h3>
            <button onclick="preloadTestModel()">预加载测试模型</button>
            <button onclick="preloadAllModels()">预加载所有模型</button>
            <button onclick="testModelLoad()">测试模型加载</button>
        </div>

        <div class="test-section">
            <h3>4. 性能测试</h3>
            <button onclick="testFirstLoad()">测试首次加载</button>
            <button onclick="testCachedLoad()">测试缓存加载</button>
            <button onclick="benchmarkLoadTimes()">性能基准测试</button>
        </div>

        <div class="test-section">
            <h3>5. 重复缓存检测</h3>
            <button onclick="testDuplicateCache()">检测重复缓存</button>
            <button onclick="fixDuplicateCache()">清理重复缓存</button>
            <div id="debug-info" class="status"></div>
            <div id="performance-results" class="status"></div>
        </div>
    </div>

    <script type="module">
        import { cacheMonitor } from './src/utils/cacheMonitor.js';

        // 测试模型URL
        const testModels = [
            'https://aiimg.huilan.com/material/model/bucket-000000/1770991377771941889.glb',
            'https://aiimg.huilan.com/material/model/bucket-000000/1845686477328011266.glb',
            'https://aiimg.huilan.com/material/model/bucket-000000/1845663967643488257.glb'
        ];

        let performanceData = {
            firstLoad: null,
            cachedLoad: null,
            benchmarkResults: []
        };

        // 缓存监控测试
        async function testDuplicateCache() {
            const { duplicateInfo } = await cacheMonitor.debugCacheInfo();
            
            if (duplicateInfo.duplicates.length > 0) {
                updateStatus('debug-info', 
                    `发现 ${duplicateInfo.duplicates.length} 个重复缓存`, 
                    'error'
                );
            } else {
                updateStatus('debug-info', 
                    `缓存正常：${duplicateInfo.uniqueCount}/${duplicateInfo.totalCount} 个模型`, 
                    'success'
                );
            }
        }

        async function fixDuplicateCache() {
            const deletedCount = await cacheMonitor.clearDuplicates();
            updateStatus('debug-info', 
                `已清理 ${deletedCount} 个重复缓存`, 
                'success'
            );
            await testDuplicateCache();
        }

        // 1. Service Worker 管理
        async function registerServiceWorker() {
            try {
                if ('serviceWorker' in navigator) {
                    const registration = await navigator.serviceWorker.register('/sw.js');
                    updateStatus('sw-status', 'Service Worker 注册成功！', 'success');
                    console.log('Service Worker registered:', registration);
                } else {
                    updateStatus('sw-status', '浏览器不支持 Service Worker', 'error');
                }
            } catch (error) {
                updateStatus('sw-status', `注册失败: ${error.message}`, 'error');
                console.error('Service Worker registration failed:', error);
            }
        }

        async function unregisterServiceWorker() {
            try {
                const registrations = await navigator.serviceWorker.getRegistrations();
                for (let registration of registrations) {
                    await registration.unregister();
                }
                updateStatus('sw-status', 'Service Worker 已注销', 'success');
            } catch (error) {
                updateStatus('sw-status', `注销失败: ${error.message}`, 'error');
            }
        }

        async function checkServiceWorkerStatus() {
            if ('serviceWorker' in navigator) {
                const registrations = await navigator.serviceWorker.getRegistrations();
                if (registrations.length > 0) {
                    updateStatus('sw-status', `Service Worker 已注册 (${registrations.length}个)`, 'success');
                    return true;
                } else {
                    updateStatus('sw-status', 'Service Worker 未注册', 'error');
                    return false;
                }
            } else {
                updateStatus('sw-status', '浏览器不支持 Service Worker', 'error');
                return false;
            }
        }

        // 2. 缓存管理
        async function checkCacheStatus() {
            if (!('caches' in window)) {
                updateStatus('cache-status', '浏览器不支持 Cache API', 'error');
                return;
            }

            try {
                const cacheNames = await caches.keys();
                const modelCache = await caches.open('ai-human-models-cache');
                const keys = await modelCache.keys();
                
                const info = {
                    cacheNames: cacheNames,
                    modelCount: keys.length,
                    models: keys.map(k => k.url)
                };

                updateStatus('cache-status', 
                    `发现 ${keys.length} 个缓存的模型`, 
                    keys.length > 0 ? 'success' : 'error'
                );

                displayModelList(info.models);
                updateDebugInfo(info);
            } catch (error) {
                updateStatus('cache-status', `检查缓存失败: ${error.message}`, 'error');
            }
        }

        async function clearAllCache() {
            try {
                const cacheNames = await caches.keys();
                await Promise.all(cacheNames.map(name => caches.delete(name)));
                updateStatus('cache-status', '所有缓存已清空', 'success');
                await checkCacheStatus();
            } catch (error) {
                updateStatus('cache-status', `清空缓存失败: ${error.message}`, 'error');
            }
        }

        // 3. 模型预加载
        async function preloadTestModel() {
            const testUrl = testModels[0];
            await preloadModel(testUrl);
        }

        async function preloadAllModels() {
            for (let url of testModels) {
                await preloadModel(url);
            }
            updateStatus('debug-info', '所有测试模型已预加载完成', 'success');
        }

        async function preloadModel(url) {
            try {
                const response = await fetch(url, {
                    headers: {
                        'Cache-Control': 'public, max-age=31536000, immutable'
                    }
                });
                
                if (response.ok) {
                    const cache = await caches.open('ai-human-models-cache');
                    await cache.put(url, response);
                    console.log('Model preloaded:', url);
                }
            } catch (error) {
                console.error('Failed to preload model:', url, error);
            }
        }

        // 4. 性能测试
        async function testModelLoad(url = testModels[0]) {
            const start = performance.now();
            
            try {
                const response = await fetch(url);
                const blob = await response.blob();
                
                const end = performance.now();
                const loadTime = end - start;
                
                updateStatus('debug-info', 
                    `模型加载完成 (${formatBytes(blob.size)}) - 耗时: ${loadTime.toFixed(2)}ms`, 
                    'success'
                );
                
                return loadTime;
            } catch (error) {
                updateStatus('debug-info', `加载失败: ${error.message}`, 'error');
                return null;
            }
        }

        async function testFirstLoad() {
            // 清除缓存后测试首次加载
            await clearAllCache();
            const loadTime = await testModelLoad();
            performanceData.firstLoad = loadTime;
        }

        async function testCachedLoad() {
            // 确保模型已缓存后测试
            await preloadModel(testModels[0]);
            const loadTime = await testModelLoad();
            performanceData.cachedLoad = loadTime;
        }

        async function benchmarkLoadTimes() {
            updateStatus('performance-results', '性能测试进行中...', 'error');
            
            const results = [];
            for (let i = 0; i < 3; i++) {
                // 清除缓存
                await clearAllCache();
                
                // 测试首次加载
                const firstLoad = await testModelLoad();
                
                // 测试缓存加载
                const cachedLoad = await testModelLoad();
                
                results.push({
                    iteration: i + 1,
                    firstLoad,
                    cachedLoad,
                    improvement: firstLoad - cachedLoad
                });
            }
            
            performanceData.benchmarkResults = results;
            displayBenchmarkResults(results);
        }

        // 5. 工具函数
        function updateStatus(elementId, message, type = '') {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.className = `status ${type}`;
        }

        function displayModelList(models) {
            const container = document.querySelector('.model-list') || 
                document.createElement('div');
            container.className = 'model-list';
            container.innerHTML = '';
            
            models.forEach(url => {
                const item = document.createElement('div');
                item.className = 'model-item cached';
                item.textContent = url.split('/').pop();
                container.appendChild(item);
            });
            
            if (!document.querySelector('.model-list')) {
                document.querySelector('.container').appendChild(container);
            }
        }

        function updateDebugInfo(info) {
            document.getElementById('debug-info').innerHTML = `
                <strong>调试信息:</strong><br>
                缓存名称: ${info.cacheNames?.join(', ') || 'N/A'}<br>
                模型数量: ${info.modelCount || 0}<br>
                总大小: ${formatBytes(info.totalSize || 0)}
            `;
        }

        function displayBenchmarkResults(results) {
            const html = results.map(r => `
                <div>
                    <strong>测试 ${r.iteration}:</strong><br>
                    首次加载: ${r.firstLoad?.toFixed(2) || 'N/A'}ms<br>
                    缓存加载: ${r.cachedLoad?.toFixed(2) || 'N/A'}ms<br>
                    性能提升: ${r.improvement?.toFixed(2) || 'N/A'}ms
                </div>
            `).join('');
            
            document.getElementById('performance-results').innerHTML = `
                <h4>性能测试结果:</h4>
                ${html}
            `;
        }

        function formatBytes(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', async () => {
            await checkServiceWorkerStatus();
            await checkCacheStatus();
        });
    </script>
</body>
</html>